package com.library.management.config;

import com.library.management.service.token.TokenService;
import com.library.management.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");
        
        // 添加调试日志
        logger.info("请求路径: " + request.getRequestURI());
        logger.info("Authorization头: " + (authorizationHeader != null ? "存在" : "不存在"));

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            try {
                username = jwtUtil.extractUsername(jwt);
                logger.info("从JWT中提取的用户名: " + username);
            } catch (Exception e) {
                logger.error("JWT token解析失败", e);
            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 验证token是否在Redis中存在
            boolean isValidToken = tokenService.validateToken(username, jwt);
            logger.info("Token验证结果: " + isValidToken);
            
            if (isValidToken) {
                try {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    logger.info("用户详情加载成功: " + username + ", 权限: " + userDetails.getAuthorities());
                    
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    logger.info("认证设置成功");
                } catch (Exception e) {
                    logger.error("加载用户详情失败: " + username, e);
                }
            } else {
                logger.warn("Token验证失败: " + username);
            }
        } else if (username == null) {
            logger.warn("无法从请求中提取用户名");
        } else {
            logger.info("用户已认证: " + username);
        }
        
        filterChain.doFilter(request, response);
    }
} 